<?php

namespace app\admin\widget;

use think\Db;

class Ui
{
    /**
     * @param $array
     * @param $config
     * @param string $selected
     * @return string
     */
    public function select($array, $config, $selected='')
    {
        try {
            $config = array_merge(['pk'=>'id', 'pid'=>'pid', 'name'=>'name'], $config);
            $tree = new \Tree($config);
            $array = $tree->getTree($array);
            $html = '';
            $selected = is_array($selected) ? $selected : explode(',', $selected);

            foreach($array as $k=>$v) {
                $html .= '<option value="'.$v[$config['pk']].'" '.(in_array($v[$config['pk']], $selected)?'selected':'').'>'.$v[$config['name']].'</option>';
            }
        } catch (\Exception $e) {
            $html = '';
        }
        if (!empty($config['has_select'])) {
            $html = '<select name="'.$config['select_name'].'" id="'.$config['select_id'].'">'.$html.'</select>';
        }

        return $html;
    }

    /**
     * 从数据表中选择
     * @param $db
     * @param $where
     * @param $config
     * @param string $selected
     * @return string
     */
    public function selectDb($db, $where, $config, $selected='')
    {
        try {
            $array = Db::name($db)->where($where)->field(isset($config['fields'])?$config['fields']:'*')->select();
        } catch (\Exception $e) {
            $array = [];
        }

        return $this->select($array, $config, $selected);
    }

    /**
     * 单图片上传
     * @param $name
     * @param string $label
     * @param string $value
     * @param bool $require
     * @param null $uploadUrl
     * @return string
     */
    public function imageUpload($name, $label='图片', $value='',$require=false, $uploadUrl=null)
    {
        $css = $js = '';
        if (!defined('LIGHTBOX')) {
            define('LIGHTBOX', 1);
            $css = $this->loadCss('/static/admin/lib/lightbox2/css/lightbox.min.css');
            $js = $this->loadJs('/static/admin/lib/lightbox2/js/lightbox.min.js');
        }
        $id = str_replace(['-', '[', ']'], '_', $name);

        if (is_null($uploadUrl)) {
            $uploadUrl = \think\Url::build('Upload/index', ['id' =>$id]);
        }
        $require = $require?'<span class="c-red">*</span>':'';
        $rule = $require ? 'datatype="*" nullmsg="请填写图片url"' : '';
        $html = <<<EOF
        <div class="row cl">
            <label class="form-label col-xs-3 col-sm-3">{$require}{$label}：</label>
            <div class="formControls col-xs-6 col-sm-6">
                <input type="text" name="{$name}" class="input-text" id="{$id}" placeholder="请点击后面的上传按钮" {$rule} style="width: 70%" value="{$value}">
                <button type="button" class="btn btn-primary radius" onclick="layer_open('文件上传','{$uploadUrl}')">上传</button>
                <a onclick="$(this).attr('href', $('#{$id}').val())" type="button" class="btn btn-success radius" data-lightbox="preview">预览</a>
            </div>
            <div class="col-xs-3 col-sm-3"></div>
        </div>
        {$css}
        {$js}
EOF;
        return $html;
    }

    public function ueditor($name,$label="内容",$value='',$require=false)
    {
        $css = $js = '';
        $url = \think\Url::build("Ueditor/index");
        if (!defined('UEDITOR')) {
            define('UEDITOR', 1);
            $css = $this->loadCss('/static/admin/lib/showdown/1.4.2/showdown.min.js');
            $js = $this->loadJs('/static/admin/lib/ueditor/1.4.3/ueditor.config.js');
            $js .= $this->loadJs('/static/admin/lib/ueditor/1.4.3/ueditor.all.min.js');
            $js .= $this->loadJs('/static/admin/lib/ueditor/1.4.3/lang/zh-cn/zh-cn.js');
            $js .= <<<EOF
        <script>window.UEDITOR_HOME_URL = '/static/admin/lib/ueditor/1.4.3/'</script>
        <script>
        function loadEditor(id){
            var ue = UE.getEditor(id,{
                serverUrl:'{$url}'
            });
            return ue;
        }
        </script>
EOF;

        }
        $id = str_replace(['-', '[', ']'], '_', $name);
        $require = $require?'<span class="c-red">*</span>':'';
        $html = <<<EOF
        <div class="row cl">
            <label class="form-label col-xs-3 col-sm-3">{$require}{$label}：</label>
            <div class="formControls col-xs-6 col-sm-6">
                <textarea name="{$name}" id="{$name}" rows="15" id="{$id}">{$value}</textarea>
            </div>
            <div class="col-xs-3 col-sm-3"></div>
        </div>
        {$css}
        {$js}
EOF;
        return $html;

    }

    protected function loadCss($url)
    {
        $html = <<<EOF
        <script type="text/javascript">
        var linkCss = document.createElement('link');
        linkCss.rel = 'stylesheet';
        linkCss.type ='text/css';
        linkCss.href = '{$url}';
        document.head.appendChild(linkCss);
        </script>
EOF;
        return $html;
    }

    protected function loadJs($url)
    {
        $html = <<<EOF
        <script type="text/javascript">
        var linkCss = document.createElement('script');
        linkCss.type ='text/javascript';
        linkCss.src = '{$url}';
        document.body.appendChild(linkCss);
        </script>
EOF;
        return $html;
    }
}